package com.example.springlearn.util.redis;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * redis String 工具类
 */
@Slf4j
@Component
public class StringUtil {

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    /**
     * 取值
     *
     * @param key 键
     * @return 值
     */
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * 存值
     *
     * @param key   键
     * @param value 值
     * @return 是否储存成功
     */
    public boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            log.warn(e.toString());
            return false;
        }
    }

    /**
     * 存值
     *
     * @param key   键
     * @param value 值
     * @param time  过期时间
     * @return 存值操作成功
     */
    public boolean set(String key, Object value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            log.warn(e.toString());
            return false;
        }
    }

    /**
     * 递增
     *
     * @param key   键
     * @param delta 增加多少
     */
    public long incr(String key, long delta) {
        if (delta <= 0) {
            throw new RuntimeException("递增因子必须大于0");
        }

        return redisTemplate.opsForValue().increment(key, delta);
    }

    /**
     * 递减
     *
     * @param key   键
     * @param delta 减少多少
     *              //@return
     */
    public long decr(String key, long delta) {
        if (delta <= 0) {
            throw new RuntimeException("递增因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, -delta);
    }
}
